﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DimensionData.Data2
{
    public abstract class DRelation
    {
        public DTable Upper { get; set; }
        public DTable Lower { get; set; }

        public DRelation NextRelation { get; set; }
        public int Level { get; set; }

        public DRelation(DTable upper, DTable lower)
        {
            Upper = upper;
            Lower = lower;
        }

        public DTree GetTree(DContext context, DTreeNode node)
        {
            DTree tree = OnGetTree(context, node);
            tree.Level = node.Tree.Level + 1;

            if (NextRelation != null)
            {
                Stack<DTreeNode> nodes = new Stack<DTreeNode>();

                for (int index = 0; index < tree.Nodes.Count; index++)
                {
                    nodes.Push(tree.Nodes[index]);
                }

                while (nodes.Count > 0)
                {
                    DTreeNode treeNode = nodes.Pop();
                    treeNode.NextTree = NextRelation.GetTree(context, treeNode);

                    for (int index = 0; index < treeNode.Nodes.Count; index++)
                    {
                        nodes.Push(treeNode.Nodes[index]);
                    }
                }
            }

            return tree;
        }

        protected abstract DTree OnGetTree(DContext context, DTreeNode node);
    }
}
